package com.ruoyi.yljf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import com.aliyun.vod.upload.impl.UploadImageImpl;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadImageRequest;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.req.UploadVideoRequest;
import com.aliyun.vod.upload.resp.UploadImageResponse;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyun.vod.upload.resp.UploadVideoResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.yljf.domain.dto.*;
import com.ruoyi.yljf.domain.vo.CreateUploadVideoResponseVO;
import com.ruoyi.yljf.domain.vo.RefreshUploadVideoResponseVO;
import com.ruoyi.yljf.service.IAliFileService;
import com.ruoyi.yljf.util.FileUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName AliFileServiceImpl
 * @Description TODO
 * @Author wangpan
 * @Date 2025/3/15 10:47
 * @Version 1.0
 **/
@Service
@Component
@Log4j2
public class AliFileServiceImpl implements IAliFileService {

    @Value("${ali.oss.access-key-id}")
    private String accessKeyId;
    @Value("${ali.oss.access-key-secret}")
    private String accessKeySecret;

    @Value("${ali.oss.image-bucket-name}")
    private String imageBucketName;
    @Value("${ali.oss.video-bucket-name}")
    private String videoBucketName;
    @Value("${ali.oss.audio-bucket-name}")
    private String audioBucketName;
    @Value("${ali.oss.file-bucket-name}")
    private String fileBucketName;
    @Value("${ali.oss.endpoint}")
    private String endpoint;


//    @Value("${ali.video.version}")
//    private String version;
//
//    @Value("${ali.video.durationSeconds}")
//    private long durationSeconds;
//
//    @Value("${ali.video.roleArn}")
//    private String roleArn;
//
//    @Value("${ali.video.roleSessionName}")
//    private String roleSessionName;
//
//    @Value("${ali.video.securityTokenRegionId}")
//    private String securityTokenRegionId;

    //点播服务所在的Region，国内请填cn-shanghai，不要填写别的区域
    private static String regionId = "cn-shanghai";

    @Override
    public AjaxResult createUploadVideo(CreateUploadVideoDTO createUploadVideoDTO){
        log.info("请求参数param={}", JSONObject.toJSONString(createUploadVideoDTO));
        DefaultAcsClient client = initVodClient();
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        AjaxResult response = new AjaxResult();
        try {
            /*必选，视频源文件名称（必须带后缀, 支持 ".3gp", ".asf", ".avi", ".dat", ".dv", ".flv", ".f4v", ".gif", ".m2t", ".m3u8", ".m4v", ".mj2", ".mjpeg", ".mkv", ".mov", ".mp4", ".mpe", ".mpg", ".mpeg", ".mts", ".ogg", ".qt", ".rm", ".rmvb", ".swf", ".ts", ".vob", ".wmv", ".webm"".aac", ".ac3", ".acm", ".amr", ".ape", ".caf", ".flac", ".m4a", ".mp3", ".ra", ".wav", ".wma"）*/
            request.setFileName(createUploadVideoDTO.getFileName());
            //必选，视频标题
            request.setTitle(createUploadVideoDTO.getTitle());
            //可选，分类ID
            request.setCateId(createUploadVideoDTO.getCateId());
            //可选，视频标签，多个用逗号分隔
            request.setTags(createUploadVideoDTO.getTags());
            //可选，视频描述
            request.setDescription(createUploadVideoDTO.getDescription());
            //可选，封面图片地址
            request.setCoverURL(createUploadVideoDTO.getCoverURL());
            CreateUploadVideoResponse createUploadVideoResponse = null;
            try {
                createUploadVideoResponse = client.getAcsResponse(request);
            } catch (ClientException e) {
                log.error("获取上传视频凭证失败，e={}",e);
            }
            CreateUploadVideoResponseVO createUploadVideoResponseVO = null;
            if (createUploadVideoResponse != null){
                createUploadVideoResponseVO = new CreateUploadVideoResponseVO();
                createUploadVideoResponseVO.setRequestId(createUploadVideoResponse.getRequestId());
                createUploadVideoResponseVO.setUploadAddress(createUploadVideoResponse.getUploadAddress());
                createUploadVideoResponseVO.setUploadAuth(createUploadVideoResponse.getUploadAuth());
                createUploadVideoResponseVO.setVideoId(createUploadVideoResponse.getVideoId());
            }
            log.info("获取上传视频凭证，response={}", createUploadVideoResponse);
            return AjaxResult.success(createUploadVideoResponseVO);

        } catch (Exception e) {
            log.error("获取上传视频凭证失败，e={}",e);
        }
        return response;
    }

    @Override
    public AjaxResult refreshUploadVideo(RefreshUploadVideoDTO videoVo){
        log.info("请求参数param={}", JSONObject.toJSONString(videoVo));
        DefaultAcsClient client = initVodClient();
        RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
        AjaxResult response = new AjaxResult();
        try {
            request.setVideoId(videoVo.getVideoId());
            RefreshUploadVideoResponse refreshUploadVideoResponse = null;
            try {
                refreshUploadVideoResponse = client.getAcsResponse(request);
            } catch (ClientException e) {
                log.error("刷新上传视频凭证失败，e={}",e);
            }
            RefreshUploadVideoResponseVO refreshUploadVideoResponseVO = null;
            if (refreshUploadVideoResponse != null){
                refreshUploadVideoResponseVO =  JSONObject.parseObject(JSONObject.toJSONString(
                        refreshUploadVideoResponse), RefreshUploadVideoResponseVO.class);
            }
            log.info("刷新上传视频凭证，response={}", refreshUploadVideoResponseVO);
            return  AjaxResult.success(refreshUploadVideoResponseVO);
        } catch (Exception e) {
            log.error("刷新上传视频凭证失败，e={}",e);
        }
        return response;
    }

    @Override
    public AjaxResult uploadVideo(VideoDTO videoVo) {
        log.info("请求参数param={}", JSONObject.toJSONString(videoVo));
        DefaultAcsClient client = initVodClient();
        try {
            UploadVideoRequest request = new UploadVideoRequest(accessKeyId, accessKeySecret, videoVo.getTitle(), videoVo.getFileName());
            UploadVideoImpl uploader = new UploadVideoImpl();
            /* 可指定分片上传时每个分片的大小，默认为1M字节 */
//        request.setPartSize(1 * 1024 * 1024L);
            UploadVideoResponse uploadVideoResponse = uploader.uploadVideo(request);
            log.info("上传本地视频，response={}", JSONObject.toJSONString(uploadVideoResponse));
            if (uploadVideoResponse.isSuccess()) {
                return AjaxResult.success(uploadVideoResponse);
            } else {
                return AjaxResult.error();
            }
        } catch (Exception e) {
            log.error("上传本地视频失败，e={}",e);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult videoFileUpload(MultipartFile file) {
//        log.info(" 请求参数param={}", JSONObject.toJSONString(file));
        DefaultAcsClient client = initVodClient();
        try {
            // 创建上传视频请求
            //title 上传之后显示的名称
            String filename = file.getOriginalFilename();//得到上传的文件名
            String title = filename.substring(0,filename.lastIndexOf("."));
//            UploadVideoRequest request = new UploadVideoRequest(accessKeyId, accessKeySecret, title,  filename);
            UploadStreamRequest request = new UploadStreamRequest(accessKeyId,accessKeySecret,title,filename,file.getInputStream());
//            request.setInputStream(file.getInputStream());  // 设置输入流
//            request.setStorageLocation("视频点播中视频的存储区域");
            request.setApiRegionId("cn-shanghai");
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
//            UploadVideoResponse uploadVideoResponse = uploader.uploadVideo(request);
            log.info(" 上传本地视频，response={}", JSONObject.toJSONString(response));
            if (response.isSuccess())  {
                System.out.println("VideoId="+response.getVideoId()+"\n");
                return AjaxResult.success(response.getVideoId());
            } else {
                return AjaxResult.error();
            }
        } catch (Exception e) {
            log.error(" 上传本地视频失败，e={}", e);
        }
        return AjaxResult.success();
    }


    @Override
    public AjaxResult uploadImage(ImageDTO imageVo) {
        log.info("请求参数param={}", JSONObject.toJSONString(imageVo));
        DefaultAcsClient client = initVodClient();
        try {
            UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, "default");
            UploadImageImpl uploadImage = new UploadImageImpl();
            request.setFileName(imageVo.getFileName());
            request.setImageType("default");
            UploadImageResponse uploadImageResponse = uploadImage.upload(request);
            log.info("上传本地图片，response={}", JSONObject.toJSONString(uploadImageResponse));
            if (uploadImageResponse.isSuccess()) {
                return AjaxResult.success(uploadImageResponse);
            } else {
                return AjaxResult.error();
            }
        } catch (Exception e) {
            log.error("上传本地图片失败，e={}",e);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult getVideoPlayAuth(RefreshUploadVideoDTO refreshUploadVideoVo){
        log.info("请求参数param={}", JSONObject.toJSONString(refreshUploadVideoVo));
        DefaultAcsClient client = initVodClient();
        AjaxResult response = new AjaxResult();
        try {
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(refreshUploadVideoVo.getVideoId());
            GetVideoPlayAuthResponse getVideoPlayAuthResponse = null;
            try {
                getVideoPlayAuthResponse = client.getAcsResponse(request);
            } catch (ClientException e) {
                log.error("获取播放视频地址失败，e={}",e);
            }
            log.info("获取播放视频凭证，response={}", getVideoPlayAuthResponse);
            return AjaxResult.success(getVideoPlayAuthResponse);

        } catch (Exception e) {
            log.error("获取播放视频凭证失败，e={}",e);
        }
        return response;
    }

    @Override
    public AjaxResult getPlayInfo(RefreshUploadVideoDTO refreshUploadVideoVo){
        log.info("请求参数param={}", refreshUploadVideoVo);
        AjaxResult response = new AjaxResult();
        String imgUrl = "";
        String filePath = "";
        HashMap<String, String> resMap = new HashMap<>();
        if (StringUtils.isBlank(refreshUploadVideoVo.getVideoId())){
            return AjaxResult.success("视频id不能为空");
        }
        DefaultAcsClient client = initVodClient();
        try {
            GetPlayInfoRequest request = new GetPlayInfoRequest();
            request.setVideoId(refreshUploadVideoVo.getVideoId());
            GetPlayInfoResponse getPlayInfoResponse = null;
            try {
                getPlayInfoResponse = client.getAcsResponse(request);
                filePath = getPlayInfoResponse.getPlayInfoList().get(0).getPlayURL();
                imgUrl = getPlayInfoResponse.getVideoBase().getCoverURL();
            } catch (ClientException e) {
                log.error("获取播放视频地址失败，e={}",e);
            }
            log.info("获取播放视频地址，response={}", getPlayInfoResponse);
            resMap.put("imgUrl",imgUrl);
            resMap.put("filePath",filePath);
            return AjaxResult.success(resMap);

        } catch (Exception e) {
            log.error("获取播放视频地址失败，e={}",e);
        }
        return response;
    }

    @Override
    public AjaxResult getSecurityToken(TokenDTO tokenVo) {
        log.info("请求参数param={}", JSONObject.toJSONString(tokenVo));
        AjaxResult response = new AjaxResult();
//        try {
//            DefaultProfile profile = DefaultProfile.getProfile(securityTokenRegionId, accessKeyId, accessKeySecret);
//            DefaultAcsClient client = new DefaultAcsClient(profile);
//            AssumeRoleResponse assumeRoleResponse = null;
//            try {
//                assumeRoleResponse = assumeRole(client, roleArn);
//            } catch (ClientException e) {
//                log.error("获取安全令牌失败，e={}",e);
//            }
//            AssumeRoleResponse.Credentials credentials = assumeRoleResponse.getCredentials();
//            log.info("获取安全令牌，response={}", response);
//            return AjaxResult.success(credentials);
//        } catch (Exception e) {
//            log.error("获取安全令牌失败，e={}",e);
//        }
        return response;
    }

    @Override
    public AjaxResult deleteVideoByCode(DeleteVideoDTO deleteVideoVo) {
        log.info("请求参数param={}", JSONObject.toJSONString(deleteVideoVo));
        AjaxResult response = new AjaxResult();
        try {
            DefaultAcsClient client = initVodClient();
            DeleteVideoRequest request = new DeleteVideoRequest();
            //多个用逗号分隔，最多支持20个
            request.setVideoIds(deleteVideoVo.getVideoId());
            DeleteVideoResponse deleteVideoResponse = client.getAcsResponse(request);
            log.info("删除视频，response={}", deleteVideoResponse);
            if (deleteVideoResponse != null && !StringUtils.isEmpty(deleteVideoResponse.getRequestId())){
                return AjaxResult.success(deleteVideoResponse);
            }else{
                return AjaxResult.error();
            }
        } catch (Exception e) {
            AjaxResult.error("视频不存在");
            log.error("删除视频失败，e={}",e);
        }
        return response;
    }

    @Override
    public AjaxResult getVideoByIds(VideoByIdsDTO videoByIdsVo) {
        log.info("请求参数param={}", JSONObject.toJSONString(videoByIdsVo));
        AjaxResult response = new AjaxResult();
        try {
            DefaultAcsClient client = initVodClient();
            GetVideoInfosRequest request = new GetVideoInfosRequest();
            //多个用逗号分隔，最多支持20个
            request.setVideoIds(videoByIdsVo.getVideoIds());

            GetVideoInfosResponse getVideoInfosResponse = client.getAcsResponse(request);
            log.info("批量获取视频，response={}", getVideoInfosResponse);
            if (getVideoInfosResponse != null && !StringUtils.isEmpty(getVideoInfosResponse.getRequestId())){
                return AjaxResult.success(getVideoInfosResponse);
            }else{
                return AjaxResult.error();
            }
        } catch (Exception e) {
            AjaxResult.error("视频不存在");
            log.error("批量获取视频失败，e={}",e);
        }
        return response;
    }

    @Override
    public String uploadFileOSS(ImageDTO imageVo) {
        OSSClient ossClient = initOSSClient();
        try {
            File file = new File(imageVo.getFilePath());
            InputStream is = new FileInputStream(file);
            // 原文件名
            String fileFullName = file.getName();
            // 原文件扩展名
            String suffix = fileFullName.substring(fileFullName.lastIndexOf("."));
            String fileName = imageVo.getFileName() + suffix;
            Long fileSize = file.length();
            // 创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            // 上传的文件的长度
            metadata.setContentLength(is.available());
            // 指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("no-cache");
            // 指定该Object下设置Header
            metadata.setHeader("Pragma", "no-cache");
            // 指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");
            // 文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
            // 如果没有扩展名则填默认值application/octet-stream
            metadata.setContentType(FileUtils.getContentType(fileFullName));
            // 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            // 上传文件 (上传文件流的形式)
            String folder = DateUtils.dateTime();
            PutObjectResult putResult = ossClient.putObject(getBucketName(fileName),  folder + "/" + fileName, is, metadata);
            // 解析结果
            log.info("上传文件result={}", JSONObject.toJSON(putResult));
            String finalUrl = "https://" + getBucketName(fileName) + ".oss-cn-shenzhen.aliyuncs.com" + "/" + folder + "/" + fileName;
            return finalUrl;
        } catch (Exception e) {
            throw new ServiceException("上传文件失败" + e.getMessage());
        } finally {
            if (ossClient != null) {
                // 关闭OSS
                ossClient.shutdown();
            }

        }
    }


    @Override
    public AjaxResult batchUpload(MultipartFile[] files) {
        OSSClient ossClient = initOSSClientV2();
        List<String> finalUrls = new ArrayList<>();
        try {
            for (MultipartFile multipartFile : files) {
                InputStream is = multipartFile.getInputStream();
                // 原文件名
                String fileFullName = multipartFile.getOriginalFilename();
                // 原文件扩展名
                String suffix = fileFullName.substring(fileFullName.lastIndexOf("."));
                String fileName = fileFullName; // 确保文件名唯一
                Long fileSize = multipartFile.getSize();

                // 创建上传Object的Metadata
                ObjectMetadata metadata = new ObjectMetadata();
                // 上传的文件的长度
                metadata.setContentLength(is.available());
                // 指定该Object被下载时的网页的缓存行为
                metadata.setCacheControl("no-cache");
                // 指定该Object下设置Header
                metadata.setHeader("Pragma",  "no-cache");
                // 指定该Object被下载时的内容编码格式
                metadata.setContentEncoding("utf-8");
                // 文件的MIME，定义文件的类型及网页编码
                metadata.setContentType(FileUtils.getContentType(fileFullName));
                // 指定该Object被下载时的名称
                metadata.setContentDisposition("filename/filesize="  + fileName + "/" + fileSize + "Byte.");
                // 上传文件 (上传文件流的形式)
                String folder = DateUtils.dateTime();
                String objectName = folder+fileName;
//                PutObjectRequest putObjectRequest = new PutObjectRequest(getBucketName(fileName), objectName, is);

//                PutObjectResult putResult = ossClient.putObject(getBucketName(fileName),  folder + "/" + fileName, is, metadata);
                // 解析结果
//                log.info(" 上传文件result={}", JSONObject.toJSON(putResult));
                // 生成文件访问URL,不要全路径
//                String finalUrl = "https://" + getBucketName(fileName) + ".oss-cn-shenzhen.aliyuncs.com"  + "/" + folder + "/" + fileName;
                String finalUrl =  "/" + folder + "/" + fileName;
                finalUrls.add(finalUrl);
            }
            String s = finalUrls.stream().collect(Collectors.joining(","));
            HashMap<String, String> resmap = new HashMap<>();
            resmap.put("resUrl",s);
            return AjaxResult.success(resmap);
        } catch (Exception e) {
            throw new ServiceException("上传文件失败：" + e.getMessage());
        } finally {
            if (ossClient != null) {
                // 关闭OSS
                ossClient.shutdown();
            }
        }
    }

    public DefaultAcsClient initVodClient() {
        DefaultAcsClient client = null;
        try {
            DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            client = new DefaultAcsClient(profile);
            log.info("initVodClient，client={}", client);
        } catch (Exception e) {
            log.error("initVodClient失败，e={}",e);
        }
        return client;
    }

    public OSSClient initOSSClient() {
        OSSClient client = null;
        try {
            client = new OSSClient(ProtocolType.HTTPS + "//" +endpoint, accessKeyId, accessKeySecret);
            log.info("initVodClient，client={}", client);
        } catch (Exception e) {
            log.error("initVodClient失败，e={}",e);
        }
        return client;
    }

    public OSSClient initOSSClientV2() {
        OSSClient client = null;
        try {
            client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            log.info("initVodClient，client={}", client);
        } catch (Exception e) {
            log.error("initVodClient失败，e={}",e);
        }
        return client;
    }

//    public AssumeRoleResponse assumeRole(
//            DefaultAcsClient client,
//            String roleArn)
//            throws ClientException {
//        final AssumeRoleRequest request = new AssumeRoleRequest();
//        try {
//            request.setVersion(version);
//            request.setMethod(MethodType.POST);
//            request.setProtocol(ProtocolType.HTTPS);
//            request.setDurationSeconds(durationSeconds);
//            request.setRoleArn(roleArn);
//            request.setRoleSessionName(roleSessionName);
//            log.info("assumeRole，request={}", request);
//        } catch (Exception e) {
//            log.error("assumeRole失败，e={}",e);
//        }
//        return client.getAcsResponse(request);
//    }

    /**
     * 通过文件名判断上传的桶名称
     *
     * @param fileName 文件名
     * @return 文件的contentType
     */
    public String getBucketName(String fileName) {
        // 文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension) || ".gif".equalsIgnoreCase(fileExtension) ||
                ".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
                || ".png".equalsIgnoreCase(fileExtension) || ".png".equalsIgnoreCase(fileExtension)) {
            return imageBucketName;
        }
        if (".html".equalsIgnoreCase(fileExtension) || ".txt".equalsIgnoreCase(fileExtension) ||
                ".vsd".equalsIgnoreCase(fileExtension) || ".ppt".equalsIgnoreCase(fileExtension) ||
                "pptx".equalsIgnoreCase(fileExtension) || ".doc".equalsIgnoreCase(fileExtension) ||
                "docx".equalsIgnoreCase(fileExtension) || ".xml".equalsIgnoreCase(fileExtension)) {
            return fileBucketName;
        }
        if (".mp4".equalsIgnoreCase(fileExtension)) {
            return videoBucketName;
        }
        if (".mp3".equalsIgnoreCase(fileExtension) || ".mp2".equalsIgnoreCase(fileExtension)) {
            return audioBucketName;
        }
        // 默认返回类型
        return fileBucketName;
    }

    public static void main1(String[] args) throws com.aliyuncs.exceptions.ClientException {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-wuhan-lr.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "yljf-image";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "test/test1.png";
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        String filePath= "G:\\avator.png";
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        String region = "cn-wuhan";

        String key = "LTAI5tD9QyTw2MxZeEY5FNtn";
        String secret = "MQSLK5SCKmcQ6P7US7XLrbx3yt4ya2";
        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
//        OSS ossClient = OSSClientBuilder.create()
//                .endpoint(endpoint)
//                .credentialsProvider(credentialsProvider)
//                .clientConfiguration(clientBuilderConfiguration)
//                .region(region)
//                .build();

        OSSClient ossClient = new OSSClient(endpoint, key, secret);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            System.out.println(JSONObject.toJSONString(result.getETag()));
            String finalUrl = "https://" + bucketName + ".oss-cn-wuhan-lr.aliyuncs.com" + "/" + "test" + "/" + "test1.png";
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
